package tr.edu.yildiz.ce.dap.amc.services.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import tr.edu.yildiz.ce.dap.amc.services.AppAuthService;
import tr.edu.yildiz.ce.dap.amc.ws.gen.AppManager;
import tr.edu.yildiz.ce.dap.amc.ws.gen.AppManagerWs;
import tr.edu.yildiz.ce.dap.amc.ws.gen.Application;
import tr.edu.yildiz.ce.dap.amc.ws.gen.ApplicationList;
import tr.edu.yildiz.ce.dap.appagent.model.App;

public class AppAuthServiceImpl implements AppAuthService {

	public void getApplications(String proxyFolder ,long id) {
		AppManager appManager = new AppManager();
		AppManagerWs appManagerWs = appManager.getAppManagerPort();
		ApplicationList applicationList = appManagerWs.listAvailableApplications(id);
		List<Application> applications = applicationList.getApplication();
		List<App> appList = new ArrayList<App>(); 
		for (Application application : applications) {
			try {
				downloadDapXml(proxyFolder, application);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private void downloadDapXml(String proxyFolder ,Application application) throws Exception{
		String dapxmlPath = null;
		try{
			URL componentUrl = new URL(application.getUrl());
			dapxmlPath = proxyFolder + "/" + application.getName() + application.getVersion()+ ".dapxml";
			File destinationFile = new File(dapxmlPath );
			if (!destinationFile.exists()){
				FileOutputStream fout = new FileOutputStream(new File(dapxmlPath ));
				InputStream uis = componentUrl.openStream();
				int r = -1;
				while ( (r=uis.read()) != -1){
					fout.write(r);
				}
				fout.close();
				uis.close();
			}
		}catch (MalformedURLException e) {
			throw new Exception("Url is not valid : " + application.getUrl() );
		}catch (IOException e) {
			throw new Exception("File can not be saved : " + dapxmlPath );
		}
	}

}
